package Demo5;

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person(10);;

        Person person1 = (Person) person.clone();//向下转型 （需要强转） 相当于Person person1 =(Person) new Object();      Object的clone方法
        System.out.println(person);
        System.out.println(person1);
        System.out.println(person.m.money);
        System.out.println(person1.m.money);
        System.out.println("*********************");
        //浅拷贝
//        person1.m.money = 99。99;
//        System.out.println(person.m.money);//99.99
//        System.out.println(person1.m.money);//99.99
        //深拷贝
        person1.m.money = 99.99;
        System.out.println(person.m.money);//19.
        System.out.println(person1.m.money);
    }
}
class Person implements Cloneable{//实现克隆接口证明当前类是可以被克隆的
    public int age;
    public Money m;
    @Override
    public String toString() {
        return "Person{" +
                " age=" + age +
                '}';
    }

    @Override
//    public Object clone() throws CloneNotSupportedException {
//        return super.clone();//super.clone    浅拷贝
//    }
       public Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();//tmp就相当于刚才的返回值
        tmp.m =(Money) this.m.clone();//person.m.clone
        return tmp;
   }

    public Person(int age) {
        this.age = age;
        this.m = new Money();
    }
}
class Money implements Cloneable{
    public double money = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}